package com.tutu.cart.service.impl;

import cn.hutool.core.util.ObjectUtil;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.tutu.cart.mapper.CartMapper;
import com.tutu.cart.service.CartService;
import com.tutu.commons.vo.CartVo;
import com.tutu.commons.clients.ProductClient;
import com.tutu.commons.pojo.Cart;
import com.tutu.commons.pojo.Product;
import com.tutu.commons.utils.R;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.LinkedHashMap;
import java.util.List;
import java.util.stream.Collectors;

/**
 * @Program: b2c-cloud-store
 * @Description:
 * @Author: JK.TuTu
 * @Version: 1.0
 * @Create: 2022-12-23 09:27
 **/
@Service
public class CartServiceImpl extends ServiceImpl<CartMapper, Cart> implements CartService {

    @Autowired
    private CartMapper cartMapper;

    @Autowired
    private ProductClient productClient;

    /**
     * 保存商品到购物车
     *
     * @param cart 用户id,商品Id
     * @return R 返回结果实体对象
     */
    @Override
    public R saveCart(Cart cart) {
        R result = productClient.getProductId(cart.getProductId());
        if (R.FAIL_CODE.equals(result.getCode())) {
            return R.fail("调用商品服务错误......");
        }
        LinkedHashMap<String, Object> map = (LinkedHashMap<String, Object>) result.getData();
        //利用fastjson中的方法将map先转换成product实体类
        Product product = JSONObject.parseObject(JSONObject.toJSONString(map), Product.class);
        //Product product = (Product) result.getData();
        if (ObjectUtil.isEmpty(product)) {
            return R.fail("系统中没有该商品!");
        }
        //检查该商品数量数量是否大于0
        if (product.getProductNum() == 0) {
            R fail = R.fail("已经没有库存,暂时无法收藏!");
            fail.setCode("003");
            return fail;
        }
        LambdaQueryWrapper<Cart> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(Cart::getProductId, product.getProductId());
        Cart cart1 = cartMapper.selectOne(queryWrapper);
        //当购物车没有该商品时 向数据库添加该商品
        if (ObjectUtil.isEmpty(cart1)) {
            Cart cart2 = new Cart();
            cart2.setProductId(cart.getProductId());
            cart2.setUserId(cart.getUserId());
            cart2.setNum(1);
            cartMapper.insert(cart2);
            CartVo cartVo = new CartVo(product, cart2);
            //返回cartVo实体
            return R.ok(cartVo);
        }
        R fail = R.fail("该商品已经在购物车");
        fail.setCode("002");
        return fail;
    }

    /**
     * 通过用户id获取购物车信息
     *
     * @param userId 用户Id
     * @return 获取到得购物车信息
     */
    @Override
    public List<Object> getCartById(Integer userId) {
        LambdaQueryWrapper<Cart> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(Cart::getUserId, userId);
        List<Cart> carts = cartMapper.selectList(queryWrapper);
        List<Object> cartvos = carts.stream().map((cart) -> {
            R result = productClient.getProductId(cart.getProductId());
            if (R.FAIL_CODE.equals(result.getCode())) {
                return R.fail("调用商品服务错误......");
            }
            LinkedHashMap<String, Object> map = (LinkedHashMap<String, Object>) result.getData();
            //利用fastjson中的方法将map先转换成product实体类
            Product product = JSONObject.parseObject(JSONObject.toJSONString(map), Product.class);
            return new CartVo(product, cart);

        }).collect(Collectors.toList());
        return cartvos;
    }

    /**
     * 更新购物车商品数量
     *
     * @param cart 购物车参数(用户id,商品id,更新过后的商品数量)
     * @return 返回结果实体对象
     */
    @Override
    public R updateCart(Cart cart) {
        R result = productClient.getProductId(cart.getProductId());
        if (R.FAIL_CODE.equals(result.getCode())) {
            return R.fail("调用商品服务错误......");
        }
        LinkedHashMap<String, Object> map = (LinkedHashMap<String, Object>) result.getData();
        Product product = JSONObject.parseObject(JSONObject.toJSONString(map), Product.class);
        //检查修改后的商品数量是否大于商品库存
        if (cart.getNum() > product.getProductNum()) {
            return R.fail("无法添加,商品库存不足!");
        }
        LambdaUpdateWrapper<Cart> updateWrapper = new LambdaUpdateWrapper<>();
        updateWrapper.eq(Cart::getUserId, cart.getUserId()).eq(Cart::getProductId, cart.getProductId());
        updateWrapper.set(Cart::getNum, cart.getNum());
        cartMapper.update(cart, updateWrapper);
        return R.ok("修改购物车数量成功!");
    }

    /**
     * 删除购物车送数据
     *
     * @param cart 购物车参数(用户id,商品id)
     * @return 返回结果实体对象
     */
    @Override
    public int removeCart(Cart cart) {
        LambdaQueryWrapper<Cart> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(Cart::getUserId, cart.getUserId()).eq(Cart::getProductId, cart.getProductId());
        return cartMapper.delete(queryWrapper);
    }

    /**
     * 删除购物车中的数据
     *
     * @param cartIds 购物车Id集合
     */
    @Override
    public void removeCarts(List<Integer> cartIds) {
        for (Integer cartId : cartIds) {
            cartMapper.deleteById(cartId);
        }
    }
}
